  // API请求工具
const API_BASE_URL = (import.meta as any)?.env?.VITE_API_BASE_URL || ''

// 创建统一的API请求函数
export async function apiRequest(endpoint: string, options: RequestInit = {}) {
  const url = endpoint.startsWith('/') ? `${API_BASE_URL}${endpoint}` : `${API_BASE_URL}/${endpoint}`

  const defaultOptions: RequestInit = {
    credentials: 'include',
    headers: {
      'Content-Type': 'application/json',
      ...options.headers,
    },
    ...options,
  }

  return fetch(url, defaultOptions)
}

// 便捷方法
export const api = {
  get: (endpoint: string, options?: RequestInit) =>
    apiRequest(endpoint, { method: 'GET', ...options }),

  post: (endpoint: string, data?: any, options?: RequestInit) => {
    const isFormData = data instanceof FormData
    return apiRequest(endpoint, {
      method: 'POST',
      body: isFormData ? data : (data ? JSON.stringify(data) : undefined),
      headers: isFormData ? {} : {
        'Content-Type': 'application/json',
      }, // 对FormData清空headers让浏览器自动设置，否则确保JSON类型
      ...options
    })
  },

  put: (endpoint: string, data?: any, options?: RequestInit) =>
    apiRequest(endpoint, {
      method: 'PUT',
      body: data ? JSON.stringify(data) : undefined,
      ...options
    }),

  delete: (endpoint: string, options?: RequestInit) =>
    apiRequest(endpoint, { method: 'DELETE', ...options }),
}

// 图片URL处理工具
export function toAbsoluteUrl(url?: string | null): string {
  if (!url) return ''
  if (url.startsWith('http')) return url
  // 相对路径需要加上API基地址
  return `${API_BASE_URL}${url}`
}

// 导出API基地址供其他地方使用
export { API_BASE_URL }
